import React from 'react';
import {Table, Spin, Card, Button, Row, Col, Form, Popconfirm} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {FORM_OPTIONS, TABLE, FORM_ROW_OPTIONS, FIXED_COLUMN_WIDTH} from '../constants';
import {addApplyReport, updateApplyReport, getDetail, getTechnicalSupportDetail} from './api';
import {getUrl} from './utils';
import TextInput from 'Shared/components/TextInput';
import ProductCategorySelectPanel from './ProductCategorySelectPanel';
import {injectIntl, language} from './intl';
import {conventEnumValueToString} from '../utils';
import {caseType, consultType} from '../Enum';
import WrappedSelect from '../common/WrappedSelect';
import styles from './style.css';
import Return from '../common/Return';
import {newOrUpdateOrderValidator} from './validator';
import FileUpload from './FileUpload';
const EMPTY_ARRAY = [];
const FormItem = Form.Item;

const caseTypeToList = caseType.toList(language);
const consultTypeToList = consultType.toList(language);
class AddPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
        showProductCategorySelectPanel: false,
        data: {
            faultCode: '',
            caseType: '',
            consultType: ''
        },
        details: [],
    }
    componentDidMount() {
        if(this.props.id) {
            this.setState({loading: true});
            getDetail(this.props.id)
                .then(res => {
                    if(res.ok)
                        this.setState({
                            loading: false,
                            data: res.data,
                            details: res.data.details
                        });
                    else
                        this.setState({loading: false});
                });
        }
        const technical = getUrl(this.props.history.location.search);
        if(technical && technical.technicalId)
            getTechnicalSupportDetail(technical.technicalId)
                .then(res => {
                    if(res.ok) {
                        const row = res.data;
                        this.setState({
                            data: Object.assign({}, this.state.data, {
                                caseType: caseType.TS,
                                consultType: row.consultType,
                                caseDescription: row.faultDescription,
                                caseAnalysis: row.measureEffects,
                                solution: row.suggestion,
                            }),
                            details: [{
                                productCategoryId: row.productCategoryId,
                                productCategoryCode: row.productCategoryCode,
                                productCategoryName: row.productCategoryName,
                            }],
                            hasOperat: true
                        });
                    }
                });
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    // eslint-disable-next-line react/sort-comp
    onChange = (value, name) => {
        if(name === 'faultCode') {
            const data = Object.assign({}, this.state.data, {
                [name]: conventEnumValueToString(caseType, this.state.data.caseType) +
                (this.state.data.consultType ? conventEnumValueToString(consultType, this.state.data.consultType).substr(0, 1) : '') +
                value.replace(conventEnumValueToString(caseType, this.state.data.caseType), '')
                    .replace((this.state.data.consultType ? conventEnumValueToString(consultType, this.state.data.consultType).substr(0, 1) : ''), '')
            });
            this.setState({
                data,
                hasOperat: true
            });
        } else if(name === 'caseType') {
            const data = Object.assign({}, this.state.data, {
                [name]: value,
                faultCode: conventEnumValueToString(caseType, value) +
                (this.state.data.consultType ? conventEnumValueToString(consultType, this.state.data.consultType).substr(0, 1) : '') +
                this.state.data.faultCode.replace(conventEnumValueToString(caseType, this.state.data.caseType), '')
                    .replace((this.state.data.consultType ? conventEnumValueToString(consultType, this.state.data.consultType).substr(0, 1) : ''), '')
            });
            this.setState({
                data,
                hasOperat: true
            });
        } else if(name === 'consultType') {
            const data = Object.assign({}, this.state.data, {
                [name]: value,
                faultCode: (this.state.data.caseType ? conventEnumValueToString(caseType, this.state.data.caseType) : '') +
                conventEnumValueToString(consultType, value).substr(0, 1) +
                this.state.data.faultCode.replace((this.state.data.caseType ? conventEnumValueToString(caseType, this.state.data.caseType) : ''), '')
                    .replace((this.state.data.consultType ? conventEnumValueToString(consultType, this.state.data.consultType).substr(0, 1) : ''), '')
            });
            this.setState({
                data,
                hasOperat: true
            });
        } else {
            const data = Object.assign({}, this.state.data, {
                [name]: value
            });
            this.setState({
                data,
                hasOperat: true
            });
        }
    }
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        const data = this.state.data;
        const details = this.state.details;
        const isValid = newOrUpdateOrderValidator(data, details);
        if(!isValid) {
            this.setState({
                isValidate: true
            });
            return;
        }
        const condition = {
            brandId: data.brandId,
            caseType: data.caseType,
            consultType: data.consultType,
            faultCode: data.faultCode,
            caseTitle: data.caseTitle,
            sultArea: data.sultArea,
            caseDescription: data.caseDescription,
            caseAnalysis: data.caseAnalysis,
            solution: data.solution,
            remark: data.remark,
            rowVersion: data.rowVersion,
            details: details.map(v => ({
                productCategoryId: v.productCategoryId,
            })),
            attachments: data.attachments.map(v => ({
                fileId: v.fileId,
                fileName: v.fileName
            }))
        };
        this.setState({loading: true});
        if(data.id)
            updateApplyReport(this.props.id, condition).then(res => {
                if(res.ok)
                    this.props.successReturn();
                if(!this.isunmount)
                    this.setState({loading: false});
            });
        else
            addApplyReport(condition).then(res => {
                if(res.ok)
                    this.props.successReturn();
                if(!this.isunmount)
                    this.setState({loading: false});
            });
    }
    removeFilePath = file => {
        const data = this.state.data;
        const index = data.attachments.findIndex(item => item.fileId === file.fileId);
        if(index === -1)
            return null;
        const attachments = data.attachments || [];
        attachments.splice(index, 1);
        this.setState({
            data: {
                ...data,
                attachments
            },
            hasOperat: true,
        });
    }
    onChangeUpload = value => {
        const data = this.state.data;
        const attachments = data.attachments || [];
        attachments.push(value[0]);
        this.setState({
            data: {
                ...data,
                attachments
            },
            hasOperat: true,
        });
    }
    onClickAddDetailBtn = () => {
        this.setState({
            showProductCategorySelectPanel: !this.state.showProductCategorySelectPanel
        });
    }
    onSelectProductCategory = value => {
        const details = this.state.details;
        value.map(p => {
            const detail = this.state.details.find(d => d.productCategoryId === p.id);
            if(!detail) {
                const detail = {
                    productCategoryId: p.id,
                    productCategoryCode: p.code,
                    productCategoryName: p.name,
                };
                details.push(detail);
            }
            return p;
        });
        this.setState({
            showProductCategorySelectPanel: false,
            hasOperat: true,
            details
        });
    }
    onDeleteAll = () => {
        this.setState({
            details: [],
            hasOperat: true
        });
    }
    onDeleteDetail = productCategoryId => {
        const details = this.state.details.filter(p => p.productCategoryId !== productCategoryId);
        this.setState({
            details,
            hasOperat: true
        });
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, details, isValidate, loading} = this.state;
        const {brands} = this.props.initEnumData;
        if(brands.length === 1 && !this.props.id) {
            data.brandId = brands[0].value;
            data.brandName = brands[0].text;
        }
        const columns = [{
            title: formatMessage({
                id: 'detailPanel.column.productCategoryCode',
                defaultMessage: '车型编号'
            }),
            dataIndex: 'productCategoryCode',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.productCategoryName',
                defaultMessage: '车型名称'
            }),
            dataIndex: 'productCategoryName',
        }, {
            title: details.length > 0
                ? (
                    <Popconfirm placement="topRight" title={formatMessage({
                        id: 'addPanel.validation.isDelete',
                        defaultMessage: '是否确认全部删除？'
                    })} onConfirm={this.onDeleteAll} >
                        <a>{formatMessage({
                            id: 'addPanel.validation.clear',
                            defaultMessage: '清空'
                        })}</a>
                    </Popconfirm>
                )
                : null,
            dataIndex: 'id',
            fixed: 'right',
            width: FIXED_COLUMN_WIDTH,
            render: (text, record) => <a data-id={text} onClick={() => this.onDeleteDetail(record.productCategoryId)}>{formatMessage({
                id: 'addPanel.validation.delete',
                defaultMessage: '删除'
            })}</a>
        }];
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'addPanel.column.common',
                        defaultMessage: '技术案例/通报管理'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.code',
                                        defaultMessage: '编号'
                                    })} {...FORM_OPTIONS.item}>
                                        {this.props.id
                                            ? data.code : <span className="value-font">{formatMessage({
                                                id: 'addPanel.value.defalut',
                                                defaultMessage: '尚未生成'
                                            })}</span>}
                                    </FormItem>
                                </Col>
                                {brands.length !== 1 && <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.brandName',
                                        defaultMessage: '品牌'
                                    })}{...FORM_OPTIONS.item} validateStatus={isValidate && !data.brandId ? 'error' : null} required>
                                        <WrappedSelect
                                            name="brandId"
                                            value={data.brandId}
                                            options={brands}
                                            onChange={this.onChange}/>
                                    </FormItem>
                                </Col>}
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.caseType',
                                        defaultMessage: '案例类型'
                                    })} {...FORM_OPTIONS.item} validateStatus={isValidate && !data.caseType ? 'error' : null} required>
                                        <WrappedSelect
                                            name="caseType"
                                            options={caseTypeToList}
                                            value={data.caseType}
                                            onChange={this.onChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.consultType',
                                        defaultMessage: '咨询类型'
                                    })} {...FORM_OPTIONS.item} validateStatus={isValidate && !data.consultType ? 'error' : null} required>
                                        <WrappedSelect
                                            name="consultType"
                                            options={consultTypeToList}
                                            value={data.consultType}
                                            onChange={this.onChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.faultCode',
                                        defaultMessage: '故障编号'
                                    })} {...FORM_OPTIONS.item} validateStatus={isValidate && !data.faultCode ? 'error' : null} required>
                                        <TextInput
                                            name="faultCode"
                                            value={data.faultCode}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.caseTitle',
                                        defaultMessage: '案例标题'
                                    })} {...FORM_OPTIONS.item} validateStatus={isValidate && !data.caseTitle ? 'error' : null} required>
                                        <TextInput
                                            name="caseTitle"
                                            value={data.caseTitle}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.sultArea',
                                        defaultMessage: '适用区域'
                                    })} {...FORM_OPTIONS.item}>
                                        <TextInput
                                            name="sultArea"
                                            value={data.sultArea}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.caseDescription',
                                        defaultMessage: '案例描述'
                                    })} {...FORM_OPTIONS.item} validateStatus={isValidate && !data.caseDescription ? 'error' : null} required>
                                        <TextInput
                                            name="caseDescription"
                                            value={data.caseDescription}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.caseAnalysis',
                                        defaultMessage: '案例分析'
                                    })} {...FORM_OPTIONS.item} validateStatus={isValidate && !data.caseAnalysis ? 'error' : null} required>
                                        <TextInput
                                            name="caseAnalysis"
                                            value={data.caseAnalysis}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.solution',
                                        defaultMessage: '解决方案'
                                    })} {...FORM_OPTIONS.item} validateStatus={isValidate && !data.solution ? 'error' : null} required>
                                        <TextInput
                                            name="solution"
                                            value={data.solution}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row className="row-margin">
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.remark',
                                        defaultMessage: '备注'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        <TextInput
                                            name="remark"
                                            type="textarea"
                                            value={data.remark}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'addPanel.operation.detail',
                            defaultMessage: '车型清单'
                        })} extra={<div>
                            <Button
                                size="small"
                                onClick={this.onClickAddDetailBtn}>
                                {formatMessage({
                                    id: 'addPanel.btn.add',
                                    defaultMessage: '增加清单'
                                })}
                            </Button>
                        </div>}>
                        <Table
                            className="white-space-nowrap"
                            columns={columns}
                            rowKey="productCategoryId"
                            pagination={false}
                            dataSource={details}
                            {...TABLE} />
                    </Card>
                    <Card title={formatMessage({
                        id: 'reportPanel.title.files',
                        defaultMessage: '附件清单'
                    })}>
                        <Row>
                            <Col {...FORM_OPTIONS.col}>
                                <FileUpload onChange={this.onChangeUpload}
                                    onRemove={this.removeFilePath}
                                    fileList={data.attachments || EMPTY_ARRAY}/>
                            </Col>
                        </Row>
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            loading={loading}>
                            {formatMessage({
                                id: 'addPanel.operation.onSubmit',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                </Spin>
                {
                    this.state.showProductCategorySelectPanel &&
                    <ProductCategorySelectPanel
                        selectKey={details.productCategoryId}
                        onCancel={this.onClickAddDetailBtn}
                        onSelect={this.onSelectProductCategory} />
                }
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

AddPanel.propTypes = {
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSelect: PropTypes.func.isRequired,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {
    tableSearch,
    saveQueryDealer
} from './actions';
import {createSelector} from 'reselect';

const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'init']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `(${item.code})${item.name}`,
            value: item.id
        })) : [];
        return {
            brands,
        };
    }
);
const mapStateToProps = state => ({
    initEnumData: getinitEnumData(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSelect: data => dispatch(saveQueryDealer(data)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(AddPanel));
